package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.ShopLink;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ShopLinkMapper;
import com.yami.shop.service.ShopLinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Random;

/**
 * 店铺链接服务实现类
 */
@Service
@Slf4j
public class ShopLinkServiceImpl extends ServiceImpl<ShopLinkMapper, ShopLink> implements ShopLinkService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<ShopLink> createShopLink(ShopLink shopLink) {
        // 参数验证
        if (shopLink.getShopId() == null) {
            throw new YamiShopBindException("店铺ID不能为空");
        }
        
        // 检查是否已存在
        ShopLink existingLink = baseMapper.getShopLinkByShopId(shopLink.getShopId());
        if (existingLink != null) {
            throw new YamiShopBindException("该店铺已存在链接");
        }
        
        // 设置默认值
        if (shopLink.getStatus() == null) {
            shopLink.setStatus(1); // 默认开启
        }
        
        Date now = new Date();
        shopLink.setCreateTime(now);
        shopLink.setUpdateTime(now);
        
        // 生成短链接
        String shortUrl = generateShortUrl(shopLink.getShopId());
        shopLink.setShortUrl(shortUrl);
        
        // 生成完整链接
        String linkUrl = "https://shop.example.com/s/" + shortUrl;
        shopLink.setLinkUrl(linkUrl);
        
        // 保存
        save(shopLink);
        
        return ResponseEntity.ok(shopLink);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> updateShopLink(ShopLink shopLink) {
        // 参数验证
        if (shopLink.getId() == null) {
            throw new YamiShopBindException("链接ID不能为空");
        }
        
        // 检查是否存在
        ShopLink existingLink = getById(shopLink.getId());
        if (existingLink == null) {
            throw new YamiShopBindException("店铺链接不存在");
        }
        
        // 设置更新时间
        shopLink.setUpdateTime(new Date());
        
        // 更新
        updateById(shopLink);
        
        return ResponseEntity.ok().build();
    }

    @Override
    public ResponseEntity<ShopLink> getShopLinkById(Long id) {
        // 参数验证
        if (id == null) {
            throw new YamiShopBindException("链接ID不能为空");
        }
        
        // 查询
        ShopLink shopLink = getById(id);
        if (shopLink == null) {
            throw new YamiShopBindException("店铺链接不存在");
        }
        
        return ResponseEntity.ok(shopLink);
    }

    @Override
    public ResponseEntity<ShopLink> getShopLinkByShopId(Long shopId) {
        // 参数验证
        if (shopId == null) {
            throw new YamiShopBindException("店铺ID不能为空");
        }
        
        // 查询
        ShopLink shopLink = baseMapper.getShopLinkByShopId(shopId);
        if (shopLink == null) {
            throw new YamiShopBindException("店铺链接不存在");
        }
        
        return ResponseEntity.ok(shopLink);
    }

    @Override
    public ResponseEntity<ShopLink> getShopLinkByShortUrl(String shortUrl) {
        // 参数验证
        if (shortUrl == null || shortUrl.isEmpty()) {
            throw new YamiShopBindException("短链接不能为空");
        }
        
        // 查询
        ShopLink shopLink = baseMapper.getShopLinkByShortUrl(shortUrl);
        if (shopLink == null) {
            throw new YamiShopBindException("店铺链接不存在");
        }
        
        // 检查状态
        if (shopLink.getStatus() == 0) {
            throw new YamiShopBindException("店铺链接已关闭");
        }
        
        return ResponseEntity.ok(shopLink);
    }

    @Override
    public ResponseEntity<IPage<ShopLink>> listShopLinksByPage(Page page, Long shopId, Integer status) {
        IPage<ShopLink> shopLinkPage = baseMapper.listShopLinksByPage(page, shopId, status);
        return ResponseEntity.ok(shopLinkPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> updateShopLinkStatus(Long id, Integer status) {
        // 参数验证
        if (id == null) {
            throw new YamiShopBindException("链接ID不能为空");
        }
        
        if (status == null || (status != 0 && status != 1)) {
            throw new YamiShopBindException("链接状态不正确");
        }
        
        // 检查是否存在
        ShopLink existingLink = getById(id);
        if (existingLink == null) {
            throw new YamiShopBindException("店铺链接不存在");
        }
        
        // 更新状态
        ShopLink shopLink = new ShopLink();
        shopLink.setId(id);
        shopLink.setStatus(status);
        shopLink.setUpdateTime(new Date());
        
        updateById(shopLink);
        
        return ResponseEntity.ok().build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<ShopLink> generateShopShortLink(Long shopId) {
        // 参数验证
        if (shopId == null) {
            throw new YamiShopBindException("店铺ID不能为空");
        }
        
        // 检查是否已存在
        ShopLink existingLink = baseMapper.getShopLinkByShopId(shopId);
        if (existingLink != null) {
            // 重新生成短链接
            String shortUrl = generateShortUrl(shopId);
            String linkUrl = "https://shop.example.com/s/" + shortUrl;
            
            existingLink.setShortUrl(shortUrl);
            existingLink.setLinkUrl(linkUrl);
            existingLink.setUpdateTime(new Date());
            
            updateById(existingLink);
            
            return ResponseEntity.ok(existingLink);
        } else {
            // 创建新链接
            ShopLink shopLink = new ShopLink();
            shopLink.setShopId(shopId);
            shopLink.setStatus(1);
            
            return createShopLink(shopLink);
        }
    }
    
    /**
     * 生成短链接
     * 
     * @param shopId 店铺ID
     * @return 短链接
     */
    private String generateShortUrl(Long shopId) {
        // 生成6位随机字符串
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        // 添加前缀
        sb.append("s");
        
        // 添加店铺ID
        sb.append(shopId % 1000);
        
        // 添加随机字符
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        
        return sb.toString();
    }
} 